<template>
  <div class="hotel-collec-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2>
            <i class="icon-star">⭐</i>
            我收藏的酒店
          </h2>
          <div class="header-subtitle">收藏优质的旅行住宿</div>
        </div>
        <div class="total-count">
          <span class="count-number">{{ filteredHotels.length }}</span>
          <span class="count-text">家酒店</span>
        </div>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-container">
      <div class="search-bar">
        <i class="search-icon">🔍</i>
        <input
          v-model="searchText"
          @input="handleSearch"
          placeholder="搜索酒店名称或相关景点"
          class="search-input"
        />
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <span class="loading-text">加载精彩内容中...</span>
    </div>

    <!-- 空状态 -->
    <div v-else-if="filteredHotels.length === 0" class="empty-state">
      <div class="empty-icon">
        <i class="icon-empty">💭</i>
      </div>
      <h3 class="empty-title">还没有收藏的酒店</h3>
      <p class="empty-description">快去发现那些优质的旅行住宿吧！</p>
      <router-link to="/homepage/hotel" class="explore-btn">
        <i class="icon-explore">🔍</i>
        探索酒店
      </router-link>
    </div>

    <!-- 酒店列表 -->
    <div v-else class="hotel-list">
      <div v-for="hotel in filteredHotels" :key="hotel.collectId" class="hotel-card">
        <!-- 整个卡片可点击区域 -->
        <div class="card-clickable-area" @click="viewDetail(hotel)">
          <!-- 图片轮播容器 -->
          <div class="hotel-img-carousel">
            <img
              :src="hotel.images[hotel.currentImg] || defaultImg"
              class="hotel-img"
              alt="酒店图片"
            />
            <div class="image-overlay"></div>
            <div class="favorite-badge">
              <i class="badge-icon">⭐</i>
            </div>
            <div class="carousel-controls" v-if="hotel.images.length > 1">
              <span
                class="carousel-arrow"
                @click.stop="prevImg(hotel)"
                :class="{ disabled: hotel.currentImg === 0 }"
              >&#8592;</span>
              <span
                class="carousel-arrow"
                @click.stop="nextImg(hotel)"
                :class="{ disabled: hotel.currentImg === hotel.images.length - 1 }"
              >&#8594;</span>
            </div>
          </div>
          
          <!-- 内容区域 -->
          <div class="hotel-content">
            <h3 class="hotel-title">{{ hotel.name }}</h3>
            
            <!-- 元信息 -->
            <div class="hotel-meta">
              <div class="meta-item">
                <i class="meta-icon">📍</i>
                <span>{{ hotel.address || '未知地址' }}</span>
              </div>
              <div class="meta-item">
                <i class="meta-icon">🏞️</i>
                <span>{{ hotel.scenic || '未知景点' }}</span>
              </div>
              <div class="meta-item">
                <i class="meta-icon">💰</i>
                <span>最低￥{{ hotel.price || '未知' }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部操作区 -->
        <div class="hotel-footer">
          <!-- 收藏时间 -->
          <div class="favorite-time">
            <i class="time-icon">⏱️</i>
            <span>{{ formatTime(hotel.favoriteTime) }}</span>
          </div>
          
          <!-- 操作按钮 -->
          <div class="hotel-actions">
            <a
              class="hotel-link"
              :href="hotel.link"
              target="_blank"
              rel="noopener noreferrer"
              @click.stop
            >
              <i class="link-icon">🔗</i>
              官网
            </a>
            <button class="collect-btn active" @click.stop="toggleCollect(hotel)" title="取消收藏">
              <i class="collect-icon">⭐</i>
              <span>已收藏</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "HotelCollec",
  data() {
    return {
      searchText: "",
      hotels: [],
      loading: true,
      defaultImg: "https://img1.baidu.com/it/u=2331851122,2068186006&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333"
    };
  },
  computed: {
    filteredHotels() {
      if (!this.searchText) return this.hotels;
      const text = this.searchText.trim().toLowerCase();
      return this.hotels.filter(
        h =>
          (h.name && h.name.toLowerCase().includes(text)) ||
          (h.scenic && h.scenic.toLowerCase().includes(text))
      );
    }
  },
  mounted() {
    this.fetchHotelCollects();
  },
  methods: {
    formatTime(time) {
      if (!time) return '';
      return time.split('T')[0];
    },
    async fetchHotelCollects() {
      this.loading = true;
      try {
        // 1. 获取当前用户userId
        const loginId = localStorage.getItem('loginId');
        if (!loginId) {
          this.hotels = [];
          this.loading = false;
          return;
        }
        
        const userRes = await fetch(`http://localhost:8080/mw/UserByLoginId?loginId=${loginId}`);
        const userData = await userRes.json();
        const userId = userData.userId;
        
        if (!userId) {
          this.hotels = [];
          this.loading = false;
          return;
        }
        
        // 2. 用 userId 查收藏酒店
        const res = await fetch(`http://localhost:8080/hotelCollect/listByUser?userId=${userId}`);
        const data = await res.json();
        
        const hotelList = [];
        for (const item of data || []) {
          let hotelDetail = {};
          try {
            const detailRes = await fetch(`http://localhost:8080/mw/hotelById?id=${item.hotelId}`);
            hotelDetail = await detailRes.json();
          } catch (e) {}
          
          let images = [];
          try {
            const imgRes = await fetch(`http://localhost:8080/api/hotelImages?hotelId=${item.hotelId}`);
            images = await imgRes.json();
          } catch (e) {}
          
          hotelList.push({
            collectId: item.id,
            id: item.hotelId,
            name: item.hotelName || hotelDetail.hotel_name || "未知酒店",
            scenic: hotelDetail.scenic_area_name || "未知景点",
            price: hotelDetail.minimum_price || "未知",
            address: hotelDetail.hotel_address || "未知地址",
            link: hotelDetail.hotel_links || "#",
            images: images.length ? images : [this.defaultImg],
            currentImg: 0,
            collected: true,
            favoriteTime: item.favoriteTime
          });
        }
        
        this.hotels = hotelList;
      } catch (error) {
        console.error('获取收藏酒店失败:', error);
        this.$message.error('获取收藏酒店失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      // 触发 computed 更新
    },
    prevImg(hotel) {
      if (hotel.currentImg > 0) hotel.currentImg--;
    },
    nextImg(hotel) {
      if (hotel.currentImg < hotel.images.length - 1) hotel.currentImg++;
    },
    viewDetail(hotel) {
      this.$router.push({ name: "HotelDetail", params: { id: hotel.id } });
    },
    async toggleCollect(hotel) {
      if (!hotel.collected) return;
      
      try {
        const res = await fetch(`http://localhost:8080/hotelCollect/delete/${hotel.collectId}`, {
          method: "DELETE"
        });
        
        if (!res.ok) {
          throw new Error('取消收藏失败');
        }
        
        this.$message.success('取消收藏成功');
        this.hotels = this.hotels.filter(h => h.collectId !== hotel.collectId);
      } catch (error) {
        console.error('取消收藏失败:', error);
        this.$message.error('取消收藏失败，请稍后重试');
      }
    }
  }
};
</script>

<style scoped>
.hotel-collec-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  margin-bottom: 24px;
}

.header-content {
  background: white;
  padding: 24px 32px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.icon-star {
  font-size: 24px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.header-subtitle {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.total-count {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: linear-gradient(135deg, #a6a6e4 0%, #c3aadd 100%);
  color: white;
  padding: 16px 20px;
  border-radius: 12px;
  min-width: 80px;
}

.count-number {
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.count-text {
  font-size: 12px;
  opacity: 0.9;
  margin-top: 4px;
}

/* 搜索栏 */
.search-container {
  margin-bottom: 24px;
  background: white;
  padding: 16px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.search-bar {
  position: relative;
  max-width: 400px;
  margin: 0 auto;
}

.search-icon {
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  color: #7f8c8d;
}

.search-input {
  width: 100%;
  padding: 12px 20px 12px 48px;
  border: 1px solid #e2e8f0;
  border-radius: 30px;
  font-size: 16px;
  transition: all 0.3s;
  background: #f8fafc;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #6b7280;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 16px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 24px;
  opacity: 0.6;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 12px 0;
}

.empty-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0 0 32px 0;
  line-height: 1.5;
}

.explore-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.explore-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

/* 酒店列表 */
.hotel-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.hotel-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
}

.hotel-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-clickable-area {
  cursor: pointer;
}

.hotel-img-carousel {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.hotel-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.hotel-card:hover .hotel-img {
  transform: scale(1.1);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.3) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.hotel-card:hover .image-overlay {
  opacity: 1;
}

.favorite-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 6px 12px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #f7b500;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.badge-icon {
  font-size: 12px;
  animation: heartbeat 1.5s ease-in-out infinite;
}

@keyframes heartbeat {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.2); }
}

.carousel-controls {
  position: absolute;
  bottom: 12px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.carousel-arrow {
  background: rgba(255, 255, 255, 0.8);
  color: #2c3e50;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.carousel-arrow:hover {
  background: white;
  transform: scale(1.1);
}

.carousel-arrow.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none !important;
}

.hotel-content {
  padding: 20px;
}

.hotel-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.hotel-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #4b5563;
}

.meta-icon {
  font-size: 16px;
  flex-shrink: 0;
}

.hotel-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
}

.favorite-time {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #6b7280;
}

.time-icon {
  font-size: 14px;
}

.hotel-actions {
  display: flex;
  gap: 8px;
}

.hotel-link {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background: #f0f4fa;
  color: #3b82f6;
  border-radius: 20px;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.hotel-link:hover {
  background: #e6f0ff;
  transform: translateY(-1px);
}

.link-icon {
  font-size: 14px;
}

.collect-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #f7b500 0%, #f59e0b 100%);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(245, 158, 11, 0.3);
}

.collect-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(245, 158, 11, 0.5);
}

.collect-btn.active {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
}

.collect-icon {
  font-size: 14px;
  animation: like-pulse 0.6s ease-in-out;
}

@keyframes like-pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.3); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hotel-collec-container {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .hotel-list {
    grid-template-columns: 1fr;
  }
  
  .hotel-footer {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .hotel-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 480px) {
  .header-content {
    padding: 20px;
  }
  
  .header-left h2 {
    font-size: 24px;
  }
  
  .hotel-content {
    padding: 16px;
  }
}
</style>